<template>
  <div class="project-list-container">
    <!-- 项目列表标题 -->
    <div class="project-list-header">
      <h1>项目列表</h1>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-filter-area">
      <div class="search-inputs">
        <div class="input-group">
          <label>项目名称</label>
          <input
            v-model="searchForm.projectName"
            type="text"
            placeholder="请输入项目名称"
            @keyup.enter="handleSearch"
            @blur="handleSearch"
          />
        </div>
        <div class="input-group">
          <label>客户名称</label>
          <input
            v-model="searchForm.customerName"
            type="text"
            placeholder="请输入客户名称"
            @keyup.enter="handleSearch"
            @blur="handleSearch"
          />
        </div>
      </div>
      <div class="action-buttons">
        <button class="create-btn" @click="handleCreateProject">创建项目</button>
      </div>
    </div>

    <!-- 项目表格 -->
    <div class="project-table-container">
      <table class="project-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>项目名称</th>
            <th>客户名称</th>
            <th>状态</th>
            <th>角色数</th>
            <th>总人数</th>
            <th>创建人</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in projectList" :key="item.id">
            <!-- 编号 -->
            <td>{{ item['686df6df33681903aca1068e'] }}</td>
            <!-- 项目名称 -->
            <td>{{ item['686df5d4fa20ded33c042478'] }}</td>
            <!-- 客户名称 -->
            <td>{{ getCustomer(item) }}</td>
            <!-- 状态 -->
            <td class="status-recruiting">{{ item['686df6df33681903aca10690'] }}</td>
            <!-- 角色数 -->
            <td>{{ item['686e48ea1f42f2639e1b9081'] }}</td>
            <!-- 总人数 -->
            <td>{{ item['686e48ea1f42f2639e1b9082'] }}</td>
            <!-- 创建人 -->
            <td>{{ item['ownerid']['fullname'] }}</td>
            <!-- 创建时间 -->
            <td>{{ item['ctime'] }}</td>
            <td class="action-cell">
              <a class="action-link view" @click="handleViewProject(item)">查看</a>
              <!-- <a class="action-link invite">邀请</a>
              <a class="action-link edit" @click="handleEditProject(item)">编辑</a>
              <a class="action-link delete" @click="handleDeleteProject(item)">删除</a> -->
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ApiService, apiService } from '@/utils/api'

const router = useRouter()

const userStore = useUserStore()

// 当前页码
const currentPage = ref(1)
// 每页显示条数
const pageSize = ref(10)
// 项目列表
const projectList = ref([])
// 总数据条数
const total = ref(0)
// 总页数
const TotalPage = ref(0)
// 搜索表单
const searchForm = ref({
  projectName: '',
  customerName: '',
})

const handleDeleteProject = async (item) => {
  await apiService.deleteRow({
    projectId: item['rowid'],
    userId: userStore.userRowid,
  })
  projectList.value = projectList.value.filter((ybb) => ybb['rowid'] !== item['rowid'])
}

const getCustomer = (project) => {
  const customerData = project['686f297f781faa1ac7bbda20']
  if (customerData === '[]') {
    return ''
  }

  try {
    const parsedData = JSON.parse(customerData)
    const sourceValue = JSON.parse(parsedData[0].sourcevalue)
    return sourceValue['686f26e30323e30ac5121f7e'] || ''
  } catch (error) {
    return ''
  }
}

const getProject = async () => {
  // 构建搜索条件
  const filters = []

  if (searchForm.value.projectName.trim()) {
    filters.push({
      controlId: '686df5d4fa20ded33c042478', // 项目名称字段ID
      dataType: 2, // 文本类型
      spliceType: 1, // AND 连接
      filterType: 1, // 模糊匹配 (1=包含, 2=等于, 3=不等于, 4=大于, 5=小于, 6=大于等于, 7=小于等于)
      value: searchForm.value.projectName.trim(),
    })
  }

  if (searchForm.value.customerName.trim()) {
    filters.push({
      controlId: '686f297f781faa1ac7bbda20', // 客户名称字段ID
      dataType: 2, // 文本类型
      spliceType: 1, // AND 连接
      filterType: 1, // 模糊匹配 (1=包含, 2=等于, 3=不等于, 4=大于, 5=小于, 6=大于等于, 7=小于等于)
      value: searchForm.value.customerName.trim(),
    })
  }

  console.log('搜索条件:', filters)
  console.log('搜索关键词 - 项目名称:', searchForm.value.projectName)
  console.log('搜索关键词 - 客户名称:', searchForm.value.customerName)

  const res = await apiService.getFilterRows({
    worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    notGetTotal: false,
    filters: filters,
  })

  console.log('API响应:', res)
  total.value = res.total
  TotalPage.value = Math.ceil(total.value / pageSize.value)
  console.log('总数:', total.value)
  console.log('总页数:', TotalPage.value)

  projectList.value = res.rows.filter((item) => item['686df6df33681903aca10690'] != '已作废')
  console.log('项目数据获取成功')
  console.log('项目列表数据:', projectList.value)

  // 安全地尝试获取第一个项目的客户信息
  if (projectList.value.length > 0) {
    try {
      const firstProject = projectList.value[0]
      const customerData = firstProject['686f297f781faa1ac7bbda20']

      if (customerData && customerData !== '[]' && customerData !== '') {
        const parsedCustomerData = JSON.parse(customerData)
        if (Array.isArray(parsedCustomerData) && parsedCustomerData.length > 0) {
          const sourceValue = parsedCustomerData[0].sourcevalue
          if (sourceValue) {
            const parsedSourceValue = JSON.parse(sourceValue)
            const customerName = parsedSourceValue['686f26e30323e30ac5121f7e']
            console.log('第一个项目的客户名称:', customerName)
          }
        }
      } else {
        console.log('第一个项目没有客户数据或客户数据为空')
      }
    } catch (error) {
      console.warn('解析项目客户数据时出错:', error)
      console.log('原始客户数据:', projectList.value[0]['686f297f781faa1ac7bbda20'])
    }
  }
}

// 处理每页显示条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  getProject()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getProject()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  getProject()
}

const addProjectList = async () => {
  const res = await apiService.getFilterRows({
    worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  })
}

// 处理创建项目按钮点击
const handleCreateProject = () => {
  router.push({ name: 'createProject' })
}

// 处理查看项目按钮点击
const handleViewProject = (item) => {
  // 根据用户权限决定跳转到不同的页面
  if (userStore.userInfo.permissions === '客户') {
    // 客户权限跳转到project_user页面
    router.push({ name: 'project_user', query: { id: item['rowid'] } })
  } else {
    // 平台权限跳转到projectDetail页面
    router.push({
      name: 'projectDetail',
      query: { id: item['rowid'] },
    })
  }
}

// 处理编辑项目按钮点击（和创建项目页面相同，但传递 item 对象）
const handleEditProject = (item) => {
  router.push({
    name: 'createProject',
    query: { id: item['rowid'] },
  })
}

onMounted(() => {
  console.log('项目页面加载完成！')
  getProject()
})
</script>

<style scoped>
.project-list-container {
  padding: 30px;
  background: linear-gradient(135deg, #f5e6f3 0%, #e8d5f0 50%, #dcc4ed 100%);
  height: 100vh;
  font-family:
    'Microsoft YaHei',
    -apple-system,
    BlinkMacSystemFont,
    sans-serif;
  display: flex;
  flex-direction: column;
  max-width: 1600px;
  margin: 0 auto;
  overflow: hidden;
}

/* 项目列表标题 */
.project-list-header {
  margin-bottom: 30px;
  text-align: left;
}

.project-list-header h1 {
  font-size: 28px;
  color: #000;
  margin: 0;
  font-weight: 600;
  text-shadow: none;
}

/* 搜索筛选区域 */
.search-filter-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background: rgba(255, 255, 255, 0.9);
  padding: 25px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.search-inputs {
  display: flex;
  gap: 25px;
  flex-wrap: wrap;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

.input-group label {
  font-size: 14px;
  color: #555;
  font-weight: 500;
  white-space: nowrap;
}

.input-group input {
  padding: 12px 16px;
  border: 2px solid #e8d5f0;
  border-radius: 12px;
  width: 220px;
  min-width: 200px;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  outline: none;
}

.input-group input:focus {
  border-color: #ec539e;
  box-shadow: 0 0 0 3px rgba(236, 83, 158, 0.1);
  background: #ffffff;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

.create-btn {
  padding: 12px 24px;
  background: #ec539e;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(236, 83, 158, 0.3);
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(236, 83, 158, 0.4);
}

.create-btn:active {
  transform: translateY(0);
}

/* 项目表格 */
.project-table-container {
  flex: 1;
  margin-bottom: 30px;
  overflow: auto;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  min-height: 0;
  position: relative;
  overflow-x: auto;
}

/* 隐藏滚动条但保持滚动功能 */
.project-table-container::-webkit-scrollbar {
  width: 0;
  height: 0;
}

.project-table-container::-webkit-scrollbar-track {
  background: transparent;
}

.project-table-container::-webkit-scrollbar-thumb {
  background: transparent;
}

.project-table {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
  table-layout: fixed; /* 固定表格布局 */
}

.project-table thead {
  position: sticky;
  top: 0;
  z-index: 10;
}

.project-table th,
.project-table td {
  padding: 12px 16px;
  text-align: left;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 设置各列的宽度 */
.project-table th:nth-child(1), /* 序号 */
.project-table td:nth-child(1) {
  width: 60px;
  min-width: 60px;
  max-width: 60px;
}

.project-table th:nth-child(2), /* 项目名称 */
.project-table td:nth-child(2) {
  width: 180px;
  min-width: 180px;
  max-width: 180px;
}

.project-table th:nth-child(3), /* 客户名称 */
.project-table td:nth-child(3) {
  width: 160px;
  min-width: 160px;
  max-width: 160px;
}

.project-table th:nth-child(4), /* 状态 */
.project-table td:nth-child(4) {
  width: 100px;
  min-width: 100px;
  max-width: 100px;
}

.project-table th:nth-child(5), /* 角色数 */
.project-table td:nth-child(5) {
  width: 70px;
  min-width: 70px;
  max-width: 70px;
}

.project-table th:nth-child(6), /* 总人数 */
.project-table td:nth-child(6) {
  width: 70px;
  min-width: 70px;
  max-width: 70px;
}

.project-table th:nth-child(7), /* 创建人 */
.project-table td:nth-child(7) {
  width: 100px;
  min-width: 100px;
  max-width: 100px;
}

.project-table th:nth-child(8), /* 创建时间 */
.project-table td:nth-child(8) {
  width: 120px;
  min-width: 120px;
  max-width: 120px;
}

.project-table th:nth-child(9), /* 操作 */
.project-table td:nth-child(9) {
  width: 220px;
  min-width: 220px;
  max-width: 220px;
}

.project-table th {
  background: linear-gradient(135deg, #f8f0f8 0%, #f0e8f8 100%);
  color: #333;
  font-weight: 600;
  border-bottom: 2px solid #e8d5f0;
  font-size: 15px;
}

.project-table td {
  border-bottom: 1px solid #f0e8f8;
  color: #555;
}

/* 项目名称和客户名称列的特殊样式 */
.project-table td:nth-child(2), /* 项目名称 */
.project-table td:nth-child(3) {
  /* 客户名称 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 0; /* 强制文本溢出省略号生效 */
}

/* 客户名称列特殊样式 */
.project-table td:nth-child(3) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 0; /* 强制文本溢出省略号生效 */
}

.project-table tbody tr:hover {
  background: linear-gradient(135deg, rgba(236, 83, 158, 0.05) 0%, rgba(156, 39, 176, 0.05) 100%);
  transition: all 0.3s ease;
}

/* 状态样式 */
.status-recruiting,
.status-confirming,
.status-confirmed,
.status-returned {
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 20px;
  display: inline-block;
  white-space: nowrap;
  min-width: fit-content;
  text-align: center;
  font-size: 13px;
}

.status-recruiting {
  color: #1890ff;
  background: transparent;
}

.status-confirming {
  color: #722ed1;
  background: rgba(114, 46, 209, 0.1);
}

.status-confirmed {
  color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
}

.status-returned {
  color: #f5222d;
  background: rgba(245, 34, 45, 0.1);
}

/* 状态列特殊样式 */
.project-table td:nth-child(4) {
  white-space: nowrap;
  overflow: visible;
  text-overflow: clip;
  min-width: 100px;
}

.action-cell {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-start;
}

.action-link {
  color: #666;
  cursor: pointer;
  font-size: 12px;
  text-decoration: none;
  padding: 4px 8px;
  border-radius: 12px;
  transition: all 0.3s ease;
  font-weight: 500;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid transparent;
  white-space: nowrap;
  min-width: fit-content;
  flex-shrink: 0;
}

.action-link:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-link.view {
  color: #1890ff;
  border-color: rgba(24, 144, 255, 0.3);
}

.action-link.view:hover {
  background: rgba(24, 144, 255, 0.1);
}

.action-link.invite {
  color: #722ed1;
  border-color: rgba(114, 46, 209, 0.3);
}

.action-link.invite:hover {
  background: rgba(114, 46, 209, 0.1);
}

.action-link.edit {
  color: #52c41a;
  border-color: rgba(82, 196, 26, 0.3);
}

.action-link.edit:hover {
  background: rgba(82, 196, 26, 0.1);
}

.action-link.delete {
  color: #f5222d;
  border-color: rgba(245, 34, 45, 0.3);
}

.action-link.delete:hover {
  background: rgba(245, 34, 45, 0.1);
}

/* 分页区域 */
.pagination-area {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px 0;
  margin-top: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  padding: 20px 25px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-filter-area {
    flex-direction: column;
    align-items: flex-start;
    gap: 20px;
  }

  .action-buttons {
    align-self: flex-end;
  }

  .search-inputs {
    gap: 20px;
  }

  .input-group input {
    width: 200px;
    min-width: 180px;
  }

  .project-table th,
  .project-table td {
    padding: 14px 16px;
    font-size: 13px;
  }

  /* 调整列宽以适应中等屏幕 */
  .project-table th:nth-child(2),
  .project-table td:nth-child(2) {
    width: 160px;
    min-width: 160px;
    max-width: 160px;
  }

  .project-table th:nth-child(3),
  .project-table td:nth-child(3) {
    width: 140px;
    min-width: 140px;
    max-width: 140px;
  }

  .project-table th:nth-child(9),
  .project-table td:nth-child(9) {
    width: 160px;
    min-width: 160px;
    max-width: 160px;
  }
}

@media (max-width: 900px) {
  .search-filter-area {
    padding: 20px;
    gap: 15px;
  }

  .search-inputs {
    gap: 15px;
    width: 100%;
  }

  .input-group {
    flex: 1;
    min-width: 0;
  }

  .input-group input {
    width: 100%;
    min-width: 0;
  }

  .action-buttons {
    align-self: stretch;
  }

  .create-btn {
    width: 100%;
  }

  .project-table-container {
    overflow-x: auto;
    border-radius: 12px;
  }

  .project-table {
    min-width: 900px; /* 确保表格有足够的最小宽度 */
  }

  .action-cell {
    gap: 8px;
    flex-wrap: nowrap;
  }

  .action-link {
    font-size: 12px;
    padding: 6px 10px;
    white-space: nowrap;
    min-width: fit-content;
  }

  /* 确保状态标签不换行 */
  .status-recruiting,
  .status-confirming,
  .status-confirmed,
  .status-returned {
    white-space: nowrap;
    min-width: fit-content;
    font-size: 12px;
    padding: 3px 10px;
  }

  /* 调整列宽以适应小屏幕 */
  .project-table th:nth-child(2),
  .project-table td:nth-child(2) {
    width: 140px;
    min-width: 140px;
    max-width: 140px;
  }

  .project-table th:nth-child(3),
  .project-table td:nth-child(3) {
    width: 120px;
    min-width: 120px;
    max-width: 120px;
  }

  .project-table th:nth-child(9),
  .project-table td:nth-child(9) {
    width: 140px;
    min-width: 140px;
    max-width: 140px;
  }
}

@media (max-width: 768px) {
  .project-list-container {
    padding: 20px;
  }

  .search-filter-area {
    padding: 18px;
    gap: 12px;
  }

  .search-inputs {
    flex-direction: column;
    width: 100%;
    gap: 12px;
  }

  .input-group {
    width: 100%;
  }

  .input-group input {
    width: 100%;
  }

  .action-buttons {
    align-self: stretch;
  }

  .create-btn {
    width: 100%;
  }

  .project-table th,
  .project-table td {
    padding: 12px 16px;
    font-size: 13px;
  }

  .project-table {
    min-width: 800px; /* 进一步减少最小宽度 */
  }

  .action-cell {
    gap: 6px;
    flex-direction: row; /* 保持水平排列 */
    align-items: center;
    flex-wrap: nowrap;
  }

  .action-link {
    font-size: 11px;
    padding: 4px 8px;
    white-space: nowrap;
    min-width: fit-content;
    flex-shrink: 0;
  }

  .status-recruiting,
  .status-confirming,
  .status-confirmed,
  .status-returned {
    font-size: 12px;
    padding: 3px 10px;
  }

  /* 进一步调整列宽 */
  .project-table th:nth-child(2),
  .project-table td:nth-child(2) {
    width: 120px;
    min-width: 120px;
    max-width: 120px;
  }

  .project-table th:nth-child(3),
  .project-table td:nth-child(3) {
    width: 100px;
    min-width: 100px;
    max-width: 100px;
  }

  .project-table th:nth-child(9),
  .project-table td:nth-child(9) {
    width: 120px;
    min-width: 120px;
    max-width: 120px;
  }
}

@media (max-width: 600px) {
  .project-list-container {
    padding: 15px;
  }

  .project-list-header h1 {
    font-size: 24px;
  }

  .search-filter-area {
    gap: 15px;
  }

  .project-table th,
  .project-table td {
    padding: 10px 12px;
    font-size: 12px;
  }

  .project-table {
    min-width: 750px; /* 最小宽度确保所有内容可见 */
  }

  .action-cell {
    gap: 4px;
  }

  .action-link {
    font-size: 10px;
    padding: 3px 6px;
  }

  .pagination-area {
    padding: 15px 20px;
  }

  /* 超小屏幕状态标签优化 */
  .status-recruiting,
  .status-confirming,
  .status-confirmed,
  .status-returned {
    font-size: 11px;
    padding: 2px 8px;
    white-space: nowrap;
    min-width: fit-content;
  }

  /* 状态列最小宽度 */
  .project-table td:nth-child(4) {
    min-width: 80px;
  }

  /* 最终调整列宽 */
  .project-table th:nth-child(2),
  .project-table td:nth-child(2) {
    width: 100px;
    min-width: 100px;
    max-width: 100px;
  }

  .project-table th:nth-child(3),
  .project-table td:nth-child(3) {
    width: 80px;
    min-width: 80px;
    max-width: 80px;
  }

  .project-table th:nth-child(9),
  .project-table td:nth-child(9) {
    width: 100px;
    min-width: 100px;
    max-width: 100px;
  }
}
</style>
